#include "htf_native_backend.h"
#include "htf_native_model_parser.h"
#include "htf_native_infer_core.h"
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>

typedef struct htf_native_backend_impl {
    htf_native_model_t* model;
    // Optional: store the model's input/output dimensions (if not included in htf_native_model_t)
    size_t input_size;
    size_t output_size;
} htf_native_backend_impl_t;

// Matching interface: int (init)(void self, const char* model_path)
static int native_init(void* self, const char* model_path) {
    htf_native_backend_impl_t* impl = (htf_native_backend_impl_t*)self;
    // Key not supported for now; pass NULL (or read from environment variable/config in the future)
    impl->model = htf_native_parse_model(model_path, NULL, 0);
    if (!impl->model) {
        return -1;
    }
    // TODO: Get the actual input/output size from impl->model
    impl->input_size = 100;   // Example value
    impl->output_size = 10;   // Example value
    return 0;
}

// Matching interface: int (run)(void self, const void* input, void* output)
static int native_run(void* self, const void* input, void* output) {
    htf_native_backend_impl_t* impl = (htf_native_backend_impl_t*)self;
    if (!impl || !impl->model) {
        return -1;
    }
    return htf_native_execute(impl->model,
                              (const float*)input, impl->input_size,
                              (float*)output, impl->output_size);
}

// Matching interface: void (destroy)(void self)
static void native_destroy(void* self) {
    htf_native_backend_impl_t* impl = (htf_native_backend_impl_t*)self;
    if (impl) {
        if (impl->model) {
            htf_native_free_model(impl->model);
        }
        free(impl);
    }
}

// The member names must exactly match those defined in htf_ai_backend_ops_t
static const htf_ai_backend_ops_t native_ops = {
    .init    = native_init,
    .run     = native_run,      // Not .infer
    .destroy = native_destroy   // Not .deinit
};

void* htf_native_backend_create(void) {
    return calloc(1, sizeof(htf_native_backend_impl_t));
}

const htf_ai_backend_ops_t* htf_native_backend_get_ops(void) {
    return &native_ops;
}